// pages/myCoupon/myCoupon.js
const app = getApp()
let staticPageNumber = 21;

// 分页 list
class TabItem {
  constructor(title) {
    this.title = title;            // 标题
    this.list = [];                // 数据列表
    this.placeholder = "点击刷新";  // 占位提示（刷新、网络错误、空白）
    this.load_type = 0;            // 0表示不显示，1表示加载中，2表示已加载全部
  }
}

// 数据item
class ListItem {
  constructor() {
    this.image_url = "../../assets/image/coupon_item_icon.png";
    this.price = ListItem.randomNumber(5, 100);
    this.title = this.price + "元红包";
    this.date = ListItem.randomNumber(2017, 2020) + "-03-02";
  }
  static randomNumber(min, max) {
    return parseInt(Math.random() * (max - min) + min);
  }
}

// 空白页tip
function getEmptyTip(index) {
  return ["暂无数据"];
}
var utilMd5 = require('../nextindex/md5.js');
Page({
  data: {
    tabs: [
      new TabItem("全部"),
      new TabItem("综合预案"),
      new TabItem("专项预案"),
      new TabItem("现场处置方案")
    ],
    stv: {
      windowWidth: 0,
      lineWidth: 0,
      offset: 0,
      tStart: false
    },
    activeTab: 0,
    hideModal: true, //模态框的状态  true-隐藏  false-显示
    animationData: {},//
    pageIndex1:1,
    pageIndex2:1,
    pageIndex3:1,
    pageIndex4:1,
    companyName:"",
    loadming:true
  },

  onLoad: function (options) {
    try {
      let { tabs } = this.data;
      var res = wx.getSystemInfoSync()
      this.windowWidth = res.windowWidth;
      // this.data.stv.lineWidth = res.windowWidth / this.data.tabs.length;
      this.data.stv.windowWidth = res.windowWidth;
      this.setData({ stv: this.data.stv })
      this.tabsCount = tabs.length;
    } catch (e) {
      // 
    }
    var that = this;
    wx.getStorage({
      key: 'user',
      success(res) {
        that.setData({
          companyName: JSON.parse(res.data).user.companyName
        })
      }
    })
    this.loadCouponsAtIndexRefresh();
  },

  onShow: function () {
    // this.setData({
    //   pageIndex1: 1
    // })
  },

  loadCouponsAtIndexRefresh(index = 0, isRefresh = true) {
    let UrlnewListhref = app.globalData.Url;
    this.setData({
      loadming: true
    })
    // loading
    wx.showLoading({
      title: '加载中',
    });

    // 显示加载更多
    if (!isRefresh) {
      // 已经加载全部，则不再请求
      let config = this.data.tabs[index];

      // 已经全部加载完毕
      if (!config.load_type == 2) {
        return;
      }

      var tabs = this.data.tabs;
      tabs[index].load_type = 1;
      this.setData({
        tabs: tabs
      })
    }
    // companyEmergencyName:"1"
    // companyId:"-1"
    // pageIndex:1
    // pageSize:10
    // planCategory:"1"
    let that = this;



    let params ={

    };
    
    wx.getStorage({
      key: 'user',
      success(res) {
        var conpanyId = JSON.parse(res.data).user.companyId;
        if (index == 0) {
          params = {
            pageIndex: that.data.pageIndex1,
            pageSize: 20,
            companyId: JSON.parse(res.data).user.companyId,
            companyEmergencyName: ""
          }
        } else if (index == 1) {
          params = {
            pageIndex: that.data.pageIndex2,
            pageSize: 20,
            companyId: JSON.parse(res.data).user.companyId,
            companyEmergencyName: "",
            planCategory: 1
          }
        } else if (index == 2) {
          params = {
            pageIndex: that.data.pageIndex3,
            pageSize: 20,
            companyId: JSON.parse(res.data).user.companyId,
            companyEmergencyName: "",
            planCategory: 2
          }
        } else if (index == 3) {
          params = {
            pageIndex: that.data.pageIndex4,
            pageSize: 20,
            companyId: JSON.parse(res.data).user.companyId,
            companyEmergencyName: "",
            planCategory: 3
          }
        }
       
        wx.request({
          url: UrlnewListhref+"/emergency/v1.0/plan/list", //仅为示例，并非真实的接口地址
          data: params,
          method: "post",
          header: {
            'content-type': 'application/json', // 默认值
            'Token': JSON.parse(res.data).token,
            'userId': JSON.parse(res.data).user.id
          },
          success(res) {
            
            wx.hideLoading();
            if (res.data.meta.success) {
                    if(index==0){
                      var indexselect = that.data.pageIndex1+1
                      that.setData({
                        pageIndex1: indexselect
                      })
                      console.log(that.data)
                    }else if(index==1){
                      that.setData({
                        pageIndex2: that.data.pageIndex2+1
                      })
                    } else if (index == 2) {
                      that.setData({
                        pageIndex3: that.data.pageIndex3+1
                      })
                    } else if (index == 3) {
                      that.setData({
                        pageIndex4: that.data.pageIndex4+1
                      })
                    }
                    var listnew = res.data.data.records;
                
                    let item = that.data.tabs[index];
                    var tips = item.placeholder;

                    var list = item.list;

                    // 请求成功
                    if (listnew && listnew.length > 0) {
                      if (isRefresh) {
                        list = [...listnew];
                      } else {
                        list.push(...listnew);
                      }

                      // 加载更多
                      var tabsNew = that.data.tabs;
                      tabsNew[index].load_type = listnew.length < staticPageNumber ? 2 : 0;
                      tabsNew[index].list = list;

                      that.setData({
                        tabs: tabsNew
                      })
                      console.log(that.data)
                      return;
                    } else {
                      tips = getEmptyTip(index);
                    }
                  
                    tips += " 点击刷新";

                    var tabs = this.data.tabs;
                    tabs[index].placeholder = tips;

                    that.setData({
                      tabs: tabs
                    })
            }else{
               that.setData({
                  loadming:false
               })
            }
          }
        })
      }
    })
  },

  // 加载更多
  loadMore(e) {
    // let currentIndex = e.currentTarget.dataset.index;
    // let currentTab = this.data.tabs[currentIndex];
    // if (currentTab.list.length > 0 && currentTab.load_type != 2) {
    //   this.loadCouponsAtIndexRefresh(currentIndex, false);
    // }
  },

  // 刷新
  refresh(e) {
    let currentIndex = e.currentTarget.dataset.index;
    let currentTab = this.data.tabs[currentIndex];
    if (currentTab.list.length <= 0) {
      this.loadCouponsAtIndexRefresh(currentIndex);
    }
  },

  // 手势开始
  handlerStart(e) {
    let { clientX, clientY } = e.touches[0];
    this.startX = clientX;
    this.tapStartX = clientX;
    this.tapStartY = clientY;
    this.data.stv.tStart = true;
    this.tapStartTime = e.timeStamp;
    this.setData({ stv: this.data.stv })
  },

  // 手势移动
  handlerMove(e) {
    let { clientX, clientY } = e.touches[0];
    let { stv } = this.data;
    let offsetX = this.startX - clientX;
    this.startX = clientX;
    stv.offset += offsetX;
    if (stv.offset <= 0) {
      stv.offset = 0;
    } else if (stv.offset >= stv.windowWidth * (this.tabsCount - 1)) {
      stv.offset = stv.windowWidth * (this.tabsCount - 1);
    }
    this.setData({ stv: stv });
  },

  // 手势取消
  handlerCancel(e) {

  },

  // 滑动手势完成
  handlerEnd(e) {
    let { clientX, clientY } = e.changedTouches[0];
    // 如果是点击手势，则屏蔽当前手势的事件处理
    if (Math.abs(this.tapStartX - clientX) < 1 && Math.abs(this.tapStartY - clientY) < 1) {
      return;
    }
    // 阻止干预scrollview的上下滑动体验
    if (Math.abs(this.data.stv.offset - 0) < 1 || Math.abs(this.data.stv.offset - this.data.windowWidth) < 1) {
      return;
    }
    let endTime = e.timeStamp;
    let { tabs, stv, activeTab } = this.data;
    let { offset, windowWidth } = stv;

    //快速滑动
    if (endTime - this.tapStartTime <= 300) {
      //向左
      if (Math.abs(this.tapStartY - clientY) < 50) {
        if (this.tapStartX - clientX > 5) {
          if (activeTab < this.tabsCount - 1) {
            let page = ++activeTab;
            this.reloadPageIfEmpty(page);
            this.setData({ activeTab: page })
          }
        } else {
          if (activeTab > 0) {
            let page = --activeTab;
            this.reloadPageIfEmpty(page);
            this.setData({ activeTab: page })
          }
        }
        stv.offset = stv.windowWidth * activeTab;
      } else {
        //快速滑动 但是Y距离大于50 所以用户是左右滚动
        let page = Math.round(offset / windowWidth);
        if (activeTab != page) {
          this.setData({ activeTab: page })
          this.reloadPageIfEmpty(page);
        }
        stv.offset = stv.windowWidth * page;
      }
    } else {
      let page = Math.round(offset / windowWidth);

      if (activeTab != page) {
        this.setData({ activeTab: page })
        this.reloadPageIfEmpty(page);
      }
      stv.offset = stv.windowWidth * page;
    }

    stv.tStart = false;
    this.setData({ stv: this.data.stv })
  },

  // item点击
  itemTap(e) {
    console.log(e);
    var url = e.currentTarget.dataset.item.newTemplateFile;
    // url ="/doc/1.pdf"
    // wx.downloadFile({  // 示例 url，并非真实存在
    //   url: url,
    //   success(res) {
    //     debugger;
    //     const filePath = res.tempFilePath
    //     wx.openDocument({
    //       filePath,
    //       fileType:"pdf",
    //       success(res) {
    //         debugger;
    //         console.log('打开文档成功')
    //       }
    //     })
    //   }
    // })
    wx.setStorage({
      key: "url",
      data: url
    })
    let baseUrl = url;
    var urlpath = baseUrl.indexOf("?") + 1;
    urlpath = baseUrl.substring(urlpath);
    var arrapi = urlpath.split("&");
    let uesrMessage = {}
    arrapi.forEach(
      (item) => {
        var brrapi = [];
        brrapi = item.split("=");
        uesrMessage[brrapi[0]] = brrapi[1];
      }
    )
    let id = uesrMessage.srcFid;
    let expires = Date.parse(new Date());
    let a = "FastDFS1234Bossien" + id + expires
    let token = utilMd5.hexMD5(a)
    token = token.toUpperCase()
    wx.getStorage({
      key: 'user',
      success(res) {
      wx.request({
        url: app.globalData.Urlnew+"/queryPublishFileInfo.do?appId=001&srcFid=" + id + "&expires=" + expires + "&token=" + token, //仅为示例，并非真实的接口地址
        data: {},
        method: "GET",
        header: {
          'content-type': 'application/json', // 默认值
          'Token': JSON.parse(res.data).token,
          'userId': JSON.parse(res.data).user.id
        },
        success(res){
          let status =res.data;
          if (!status.success) {
            wx.showToast({
              title: '文件正在转码中，请稍后再查看',
              icon: 'none',
              duration: 1000
            })
            return false;
          }
          if (status.dataObj.srcFileStatusName == "12") {
            wx.navigateTo({
              url: '../myCouponDetail/index'
            })
          } else {
            wx.showToast({
              title: '文件正在转码中，请稍后再查看',
              icon: 'none',
              duration: 1000
            })
          }
        }
      })  
      }
    })   
    

     

  },

  // 更新选中的page
  updateSelectedPage(page) {
    // 屏蔽重复选中
    if (this.data.activeTab == page) {
      return;
    }
    let { tabs, stv, activeTab } = this.data;
    activeTab = page;
    this.setData({ activeTab: activeTab })
    stv.offset = stv.windowWidth * activeTab;
    this.setData({ stv: this.data.stv })
    this.reloadPageIfEmpty(page);
  },

  reloadPageIfEmpty(page) {
    // 重新请求
    if (this.data.tabs[page].list.length <= 0) {
      this.loadCouponsAtIndexRefresh(page);
    }
  },

  // item view 点击
  handlerTabTap(e) {
    this.updateSelectedPage(e.currentTarget.dataset.index);
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '应急预案智能管理小助手',
      path: '/page/nextindex/index'
    }
  },

  showModal: function () {
    var that = this;
    that.setData({
      hideModal: false
    })
    var animation = wx.createAnimation({
      duration: 600,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeIn();//调用显示动画

    // setTimeout(function () {
    // }, 200)  
  },
  hideModal: function () {
    var that = this;
    var animation = wx.createAnimation({
      duration: 800,//动画的持续时间 默认400ms   数值越大，动画越慢   数值越小，动画越快
      timingFunction: 'ease',//动画的效果 默认值是linear
    })
    this.animation = animation
    that.fadeDown();//调用隐藏动画 
    that.setData({
      hideModal: true
    })
    // setTimeout(function () {

    // }, 720)//先执行下滑动画，再隐藏模块

  },

  //动画集
  fadeIn: function () {
    this.animation.translateY(0).step()
    this.setData({
      animationData: this.animation.export()//动画实例的export方法导出动画数据传递给组件的animation属性
    })
  },
  fadeDown: function () {
    this.animation.translateY(300).step()
    this.setData({
      animationData: this.animation.export(),
    })
  },
  togofrinend(){
    wx.navigateTo({
      url: '../friendshare/index'
    })
  },
  dolookList(){
     
  }
})